
from typing import Any
from utils.tokenUtil import analysis_token, verify_token_format

# 解析token装饰器
def analysis_token_decorator(func):
    async def wrapper(session, token):
        token_str_list = await verify_token_format(token)
        payload = await analysis_token(token_str_list[1])
        return await func(session, payload["sub"])

    return wrapper

# 事务处理装饰器
def transaction_decorator(func):
    # async def wrapper(self, session, *params, **kwparams):
    async def wrapper(session, *params):
        try:
            # await func(self, session, *params, **kwparams)
            await func(session, *params)

        except Exception as e:
            await session.rollback()
            await session.close()

            return {"message": "数据库操作失败", "code": 500, "errors": repr(e)}
        else:
            await session.commit()

        finally:
            await session.close()

        return {"message": "操作成功", "code": 200, "data": None}

    return wrapper

# 事务处理装饰器同步
def transaction_decorator_sync(func):
    def wrapper(session, *params):
        try:
            func(session, *params)

        except Exception as e:
            session.rollback()
            session.close()

            return {"message": "数据库操作失败", "code": 500, "errors": repr(e)}
        else:
            session.commit()

        finally:
            session.close()

        return {"message": "操作成功", "code": 200, "data": None}

    return wrapper

# 失败回写装饰器
def write_back(func):
    def wrapper(self, current_info, ident, *params):
        try:
            func(self, *params)
        except Exception as e:
            ident["end"] = True
            self.update_whether(current_info, e, "fail", "FFC125")
            self.save_excel()

    return wrapper













